﻿using System;
using System.Web.Mvc;
using BisinessLogic;
using Domain.Entities;
using Web.Models;
using Web.ViewModels;


namespace Web.Controllers
{
    public class ShoppingCartController : Controller
    {
        private DataManager storeDB;
        public ShoppingCartController(DataManager dataManager)
        {
            storeDB = dataManager;
        }

        public ActionResult Index()
        {
            var cart = ShoppingCart.GetCart(this.HttpContext);
            var viewModel = new ShoppingCartViewModel
            {
                CartItems = cart.GetCartItems(),
                CartTotal = cart.GetTotal()
            };
            return View(viewModel);
        }
        [HttpPost]
        public ActionResult AddToCart(int id)
        {
            int count = 0;
            try
            {
                ProduceInPackage package = storeDB.ProduceInPackages.GetProduceInPackageById(id);
                var cart = ShoppingCart.GetCart(this.HttpContext);
                cart.AddToCart(package);
                count = cart.GetCount();
            
            }
            catch (Exception)
            {
                return Json(new
                {
                    success = false
                });
            }
            return Json(new
            {
                success = true,
                itemCount= count          
            });
        }

        // AJAX: /ShoppingCart/RemoveFromCart/5
        [HttpPost]
        public ActionResult RemoveFromCart(int id)
        {
            var c = storeDB.Carts.GetCartById(id);
            string name = c.Produce.Name;

            var cart = ShoppingCart.GetCart(this.HttpContext);

            // удаление
            int itemCount = cart.RemoveFromCart(id);

            // Display the confirmation message
            var results = new ShoppingCartRemoveViewModel
            {
                Message = Server.HtmlEncode(name) +
                    " был удален с вашей корзины",
                CartTotal = cart.GetTotal(),
                CartCount = cart.GetCount(),
                ItemCount = itemCount,
                DeleteId = id
            };

            return Json(results);
        }

        [ChildActionOnly]
        public ActionResult CartSummary()
        {
            var cart = ShoppingCart.GetCart(this.HttpContext);

            ViewData["CartCount"] = cart.GetCount();
            return PartialView("CartSummary");
        }

        [HttpPost]
        public ActionResult CleanCart()
        {
            try
            {
                var cart = ShoppingCart.GetCart(this.HttpContext);
                cart.EmptyCart();
            }
            catch (Exception)
            {
                return Json(new { success = false });
            }
            return Json(new { success = true });
        }


    }

}